package sort.impl;

import anaydis.sort.SorterType;
import com.sun.istack.internal.NotNull;

import java.util.Comparator;
import java.util.List;

public class QuickSorterMedianOfThree extends AbstractQuickSorter {

    public QuickSorterMedianOfThree() {
        super(SorterType.QUICK_MED_OF_THREE);
    }

    public <T> void sort(@NotNull Comparator<T> tComparator, @NotNull List<T> ts) {
         sort(tComparator,ts,0,ts.size()-1);
    }

    private <T> void sort(Comparator<T> comparator, List<T> list, int start, int end) {
        if (end <= start) return;
        if(end-start>3){
            getMedian(comparator,list, end);
        }
        int i = partition(comparator, list, start, end);
        sort(comparator, list, start, i - 1);
        sort(comparator, list, i, end);
    }

    private <T>void getMedian(Comparator<T> comparator, List<T> list, int right){
        int left = right-2;
        int middle = right-1;
        if((greater(comparator, list, middle, right)&&(!greater(comparator, list, middle,left)))||(
                !greater(comparator, list, middle, right)&&(greater(comparator, list, middle,left)))){
            swap(list,middle,right);
        } else if ((greater(comparator, list, left, right)&&(!greater(comparator, list, left,middle)))||
                (!greater(comparator, list, left, right)&&(greater(comparator, list, left,middle)))){
            swap(list,left,right);
        }

    }
}
